package Problem3;
import java.util.Arrays;
public class MyArrayList <E>{
    private int defaultLength = 10;
    private Object[] arr = new Object[defaultLength];
    private int size = 0;

    public MyArrayList() {
    }
    //添加数据
    public boolean add(E e){
        //先判断arr数组是否要扩容
        if (isExpansion()){
            //已经扩容成功
            System.out.println("已经扩容了");

        }
        arr[size++] = e;
        return true;
    }
    //查询数据
    public E get(int index){
        if(index >= size || index < 0){
            throw new RuntimeException();
        }
        else {
            return (E)arr[index];
        }
    }
    //删除数据
    public E remove(int index) {
        if (index >= size || index < 0) {
            throw new RuntimeException();
        } else {
            E retainData = (E) arr[index];
            if (index != size - 1) {
                //1,2,3,4,5,6
                //0,1,2,3,4,5
                //int remainder = size - index - 1;
                for (int i = index; i < size - 1; i++) {
                    arr[i] = arr[i + 1];
                }
            }
            size--;
            return retainData;
        }
    }
    //获取集合大小size
    public int size(){
        return size;
    }
    //开发一个forEach方法
    public void forEach(MyConsumer myConsumer){
        for (int i = 0; i < size; i++) {
            myConsumer.accept(arr[i]);
        }
    }
    private boolean isExpansion(){
        if (size >= defaultLength){
            defaultLength = (int) (defaultLength * (1.5));
            Object[] temp = new Object[defaultLength];
            for (int i = 0; i < size; i++) {
                temp[i] = arr[i];
            }
            arr = temp;
            return true;
        }else {
            return false;
        }
    }

    @Override
    public String toString() {
        Object[] temp = new Object[size];
        for (int i = 0; i < size; i++) {
            temp[i] = arr[i];
        }
        return Arrays.toString(temp);
    }
}
